<?php

require_once('dbconnect.inc.php');

$sth = $dbh->query('select * from msg_template');

$templates = array();

if ($recs = $sth->fetchAll())
{
    foreach($recs as $key => $value)
    {
        $templates[$value['t_id']+1] = $value['template'];
    }
}
else
{
    die();
}

function get_text($_problem, $_channel, $_c_id, $_loc)
{
    global $templates;
    
    $result = preg_replace('/%c/suU', $_c_id ,$templates[$_problem]);
    $result = preg_replace('/%l/suU', $_loc ,$result);
    $result = preg_replace('/%z/suU', $_channel ,$result);
    
    return $result;
}

function get_notify_for($_name)
{
    global $dbh;
    
    $result = array();
    
    $sth = $dbh->query("SELECT log.log_id, date_format(log.log_date, '%d.%m.%Y %k:%m:%s') as date, log.log_fault, log.c_id, nm.location FROM log, network_map nm where nm.c_id = log.c_id and imp > 1 and log_notify_date is null and nm.notify_$_name=1");
    
    if ($all = $sth->fetchAll())
    {
        foreach($all as $key => $value)
        {
            $fault = intval($value['log_fault']);
            
            if ($fault > 0)
            {
                $result[] = '[' . $value['date'] . '] ' . get_text($fault >> 8, $fault & 0xff, intval($value['c_id']), $value['location']);
            }               
            
        }
    }
    
    return $result;
}

function cleanup_all_notify()
{
  global $dbh;
  
  $dbh->exec("update log set log_notify_date = NOW() where imp > 1 and log_notify_date is null");
}

function get_list($_type)
{
    global $dbh;
    $result = array();
    
    $sth = $dbh->query("select notify_info as num from msg_setup where notify_type=$_type");
    
    if ($all = $sth->fetchAll())
    {
        foreach($all as $key => $value)
        {
                $result[] = $value['num'];
        }
    }
    return $result;
}


$text = get_notify_for('email');

if (!empty($text))
{
    $email_list = get_list(1);

    foreach($email_list as $pkey => $email)
    {
        $body = "На светофорном обьекте возникли следующиий проблемы:\r\n\r\n" . implode("\r\n", $text) . "\r\n\r\nЭто письмо отправлено роботом !\r\nНет смысла отвечать на него.\r\n";
        $headers = "From: auto-notify-system\r\nMime-Version: 1.0\r\nContent-Type: text/plain; charset=\"UTF-8\"\r\nContent-Transfer-Encoding: 8bit";
        $subject = '=?utf-8?B?' . base64_encode("Уведомление о проблемах сфетофорного обьекта.") . "?=";

        mail($email, $subject , $body, $headers);
    }
}

$text = get_notify_for('sms');

if (!empty($text))
{
    $phone_list = get_list(0);
    
    foreach($phone_list as $pkey => $value)
    {
        foreach($text as $mkey => $mvalue)
        {
            $cmd = "echo $mvalue | gammu sendsms text $value -unicode &> /dev/null";
            exec($cmd);
        }
    }
}

cleanup_all_notify();

?>
